define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'project_assess/index' + location.search,
                    add_url: 'project_assess/add',
                    edit_url: 'project_assess/edit',
                    del_url: 'project_assess/del',
                    multi_url: 'project_assess/multi',
                    import_url: 'project_assess/import',
                    detail_url: 'project_assess/detail',
                    importformal_url: 'project_assess/importformal',
                    table: 'project_rencaiji',
                }
            });

            var table = $("#table");
            var projectConfig = Config.projectConfig;

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                height:700,
                fixedColumns: true,
                fixedNumber: 3,
                columns: [
                    [
                        {checkbox: true,formatter: function(value, row, index) {
                            return {
                                disabled: !(Config.childrenAdminIds.indexOf(row.admin_id) > -1)
                            };
                        }},
                        {field: 'id', title: __('序号'),sortable:true, searchable:false},
                        {field: 'name', title: __('Name'), align: 'left',cellStyle:function (value,row,index,field) {
                            return {
                                css: {
                                    "min-width": "150px",
                                    "white-space": "nowrap",
                                    "text-overflow": "ellipsis",
                                    "overflow": "hidden",
                                    "max-width":"300px",
                                    'cursor':"pointer"
                                }
                            };
                        }, formatter:function (value, row, index) {
                            return "<a href='javascript:void(0);' style='color: #4397fd' class='btn-dialog' " +
                                        "data-url='project_assess/detail/ids/"+row.id+"' data-title='项目详情' data-area=[\"100%\",\"100%\"]  title='"+row.name+"'>" + row.name + "</a>";
                        }},
                        {field: 'catename', title: __('Catename')},
                        {field: 'description', title: __('Description')},
                        {field: 'unit', title: __('Unit')},
                        {field: 'tax', title: __('Tax')},
                        {field: 'reference_price', title: __('Reference_price'),sortable:true},
                        {field: 'unit_price', title: __('Unit_price'),sortable:true},
                        {field: 'total_price', title: __('Total_price')},
                        {field: 'project.project_name', title: __('Project_name'), operate: 'LIKE', formatter:function (value, row, index) {
                            return "<a href='javascript:void(0);' style='color: #4397fd' class='btn-dialog' " +
                                        "data-url='project/detail/ids/"+row.project_id+"' data-title='项目详情' data-area=[\"100%\",\"100%\"] >" + row.project.project_name + "</a>";
                        }},
                        {field: 'project.project_address', title: __('Project_address'), operate: 'LIKE'},
                        {field: 'project.pricing_date', title: __('Pricing_date'), operate: 'RANGE',datetimeFormat:'YYYY-MM-DD', formatter: Table.api.formatter.datetime, addclass:'datetimerange',},
                        {field: 'project.project_class', title: __('Project_class'), searchList: projectConfig.project_class, formatter: Table.api.formatter.normal},
                        {field: 'project.project_bulid_cost', title: __('Project_bulid_cost'), operate:'BETWEEN'},
                        {field: 'project.project_scale', title: __('Project_scale'), operate:'BETWEEN'},
                        // {field: 'square_build_cost', title: __('Square_build_cost'), operate:'BETWEEN'},
                        {field: 'project.build_unit', title: __('Build_unit')},
                        {field: 'project.construction_unit', title: __('Construction_unit')},
                        {field: 'project.structure_type', title: __('Structure_type'), searchList: projectConfig.structure_type, formatter: function (value, row, index) {
                            return projectConfig.structure_type[value] || '-';
                        }},
                        {field: 'project.build_cost_type', title: __('Build_cost_type'), searchList: projectConfig.build_cost_type, formatter: function (value, row, index) {
                            return projectConfig.build_cost_type[value] || '-';
                        }},
                        {field: 'project.build_form', title: __('Build_form'), searchList: projectConfig.build_form, formatter: function (value, row, index) {
                            return projectConfig.build_form[value] || '-';
                        }},
                        {field: 'project.taxation_type', title: __('Taxation_type'), searchList: projectConfig.taxation_type, formatter: function (value, row, index) {
                            return projectConfig.taxation_type[value] || '-';
                        }},
                        {field: 'project.contract_no', title: __('Contract_no')},
                        // {field: 'start_date', title: __('Start_date'), operate:'RANGE', addclass:'datetimerange', autocomplete:false},
                        // {field: 'end_date', title: __('End_date'), operate:'RANGE', addclass:'datetimerange', autocomplete:false},
                        // {field: 'real_start_date', title: __('Real_start_date'), operate:'RANGE', addclass:'datetimerange', autocomplete:false},
                        // {field: 'real_end_date', title: __('Real_end_date'), operate:'RANGE', addclass:'datetimerange', autocomplete:false},
                        // {field: 'project_params', title: __('Project_params'), operate: 'LIKE'},
                        // {field: 'pricing_method', title: __('Pricing_method')},
                        // {field: 'pricing_basis', title: __('Pricing_basis')},
                        // {field: 'pricing_inventory', title: __('Pricing_inventory')},
                        // {field: 'senior_editor_date', title: __('Senior_editor_date'), operate:'RANGE', addclass:'datetimerange', autocomplete:false},
                        // {field: 'quota_days', title: __('Quota_days')},
                        // {field: 'contract_days', title: __('Contract_days')},
                        // {field: 'real_days', title: __('Real_days')},
                        // {field: 'prepared_date', title: __('Prepared_date'), operate:'RANGE', addclass:'datetimerange', autocomplete:false},
                        // {field: 'prepared_by', title: __('Prepared_by'), operate: 'LIKE'},
                        // {field: 'build_unit', title: __('Build_unit'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        // {field: 'compilation_unit', title: __('Compilation_unit'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        // {field: 'review_unit', title: __('Review_unit'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        // {field: 'contacts', title: __('Contacts'), operate: 'LIKE'},
                        // {field: 'contact_mobile', title: __('Contact_mobile'), operate: 'LIKE'},
                        // {field: 'constact_email', title: __('Constact_email'), operate: 'LIKE'},
                        // {field: 'project_files', title: __('Project_files'), operate: false, formatter: Table.api.formatter.files},
                        {field: 'admin.nickname', title: __('Admin_id')},
                        {field: 'isimport', title: __('Isimport'), searchList:{'1':'已导入','0':'未导入'}, formatter: Table.api.formatter.normal},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        // {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ]
            });
            $(document).on("click",'#importSelect',function() {
                var ids = Table.api.selectedids(table);
                var page = table.bootstrapTable('getData');
                var all = table.bootstrapTable('getOptions').totalRows;
                var search = table.bootstrapTable('getOptions').queryParams({});
                var filter = search.filter
                var op = search.op
                Layer.confirm("请选择导入材价库的选项", {
                    title   : '导入数据',
                    btn     : ["选中项(" + ids.length + "条)", "本页(" + page.length + "条)", "全部(" + all + "条)"],
                    success : function (layero, index) {
                        $(".layui-layer-btn a", layero).addClass("layui-layer-btn0");
                    }, yes   : function (index, layero) {
                        if (ids.length == 0) {
                            Layer.alert('数据为空');
                            return true;
                        }
                        $.post($.fn.bootstrapTable.defaults.extend.importformal_url, {type:1,ids : ids.join(","), isall : 1}, function (res) {
                            if(res.code == 1){
                                Layer.alert(res.msg);
                                Layer.close(index);
                                location.reload();
                            }else{
                                Layer.alert(res.msg);
                            }
                        }, 'json');
                        return false;
                    },
                    btn2    : function (index, layero) {
                        if (page.length == 0) {
                            Layer.alert('数据为空');
                            return true;
                        }
                        var ids = [];
                        $.each(page, function (i, j) {
                            ids.push(j.id);
                        });
                        $.post($.fn.bootstrapTable.defaults.extend.importformal_url, {type:1, ids : ids.join(","), isall : 2}, function (res) {
                            if(res.code == 1){
                                Layer.alert(res.msg);
                                Layer.close(index);
                                location.reload();
                            }else{
                                Layer.alert(res.msg);
                            }
                        }, 'json');
                        return false;
                    },
                    btn3    : function (index, layero) {
                        if (page.length == 0) {
                            Layer.alert('数据为空');
                            return true;
                        }
                        $.post($.fn.bootstrapTable.defaults.extend.importformal_url+'?filter='+filter+'&op='+op, {type:1, ids : ids.join(","), isall : 3}, function (res) {
                            if(res.code == 1){
                                Layer.alert(res.msg);
                                Layer.close(index);
                                location.reload();
                            }else{
                                Layer.alert(res.msg);
                            }
                        }, 'json');
                        return false;
                    }
                })
            });
            $(document).on("click",'#importProject',function() {
                Fast.api.open($.fn.bootstrapTable.defaults.extend.importformal_url, "按项目及类别筛选导入材价库", {area:["50%","50%"]});
            });
            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        recyclebin: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    'dragsort_url': ''
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: 'project_assess/recyclebin' + location.search,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {
                            field: 'deletetime',
                            title: __('Deletetime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'operate',
                            width: '140px',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'Restore',
                                    text: __('Restore'),
                                    classname: 'btn btn-xs btn-info btn-ajax btn-restoreit',
                                    icon: 'fa fa-rotate-left',
                                    url: 'project_assess/restore',
                                    refresh: true
                                },
                                {
                                    name: 'Destroy',
                                    text: __('Destroy'),
                                    classname: 'btn btn-xs btn-danger btn-ajax btn-destroyit',
                                    icon: 'fa fa-times',
                                    url: 'project_assess/destroy',
                                    refresh: true
                                }
                            ],
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },

        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        import: function () {
            Controller.api.bindevent();
        },
        detail: function () {
            $(document).on('click','#edits',function () {
                var id=$('#ids').val();
                Fast.api.open("project_assess/edit?ids="+id, "材料编辑",{
                    shadeClose: false,
                    shade: false,
                    maxmin: false,
                    moveOut: false,
                    scrollbars:false,
                    area:["95%","95%"],
                    callback:function(value){
                        location.reload();
                    },
                });

            })
            Controller.api.bindevent();
        },
        importformal:function() {
            $(document).on("change", "#c-project_id", function(){
                var project_id = $(this).val();
                $("#c-catename_text").data('selectPageObject').option.params = function () {
                    return {custom: {project_id: project_id}};
                };
                // 清空当前选择并刷新SelectPage
                $("#c-catename").val('').trigger('change').data("selectPage")?.refresh()
            });
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
                let originalData = []; // 用于存储原始数据
                let batchtimes = 0;
                let curtimes = 0;
                let lastrow = 0;
                $("#c-file").change(function () {
                    var listfile = $(this).val();
                    if (listfile) {
                        var that = this
                        that.layerIndex =layer.load(0,{ shade: 0.3 });
                        $.ajax({
                            url: "project_assess/import_preview",
                            data: {listfile: listfile},
                            type: "post",
                            complete: function(){
                                layer.close(that.layerIndex);
                            },
                            success: function (res) {
                                if (res.code == 1) {
                                    originalData = res.data.data;
                                    batchtimes = res.data.batchtimes;
                                    layer.msg(res.msg,{time:1000},function (){
                                        var htm = `<table class="table table-striped table-config" id="normaledit">
                                                    <tbody>
                                                    <tr>
                                                        <td width="60">Excel行号</td>
                                                        <td>类别</td>
                                                        <td>编号</td>
                                                        <td>材料名称</td>
                                                        <td width="100">规格型号</td>
                                                        <td>单位</td>
                                                        <td width="60">数量</td>
                                                        <td width="60">税率(%)</td>
                                                        <td width="100">评审参考价(元)</td>
                                                        <td width="100">市场单价(元)</td>
                                                        <td width="100">市场合价(元)</td>
                                                    </tr>
                                                    `;
                                        for (var i=0;i<originalData.length;i++){
                                            numcount = originalData[i].hang
                                            htm += `<tr>
                                                        <td>${originalData[i].hang}</td>
                                                        <td>${originalData[i].catename}</td>
                                                        <td>${originalData[i].code}</td>
                                                        <td>${originalData[i].name}</td>
                                                        <td>${originalData[i].description}</td>
                                                        <td>${originalData[i].unit}</td>
                                                        <td>${originalData[i].quantity}</td>
                                                        <td>${originalData[i].tax}</td>
                                                        <td>${originalData[i].reference_price}</td>
                                                        <td>${originalData[i].unit_price}</td>
                                                        <td>${originalData[i].total_price}</td>`;
                                            htm += ` </tr>`;
                                        }
                                        htm += `</tbody>
                                                    </table>`;
                                        $("#wechat").empty();
                                        $("#wechat").html(htm);
                                    });
                                } else {
                                    layer.msg(res.msg);
                                    return false;
                                }
                            }
                        });
                    }
                });
                var submit = function(form, success, error, submit) {
                    if (form.size() === 0) {
                        Toastr.error("表单未初始化完成,无法提交");
                        return false;
                    }
                    if (typeof submit === 'function') {
                        if (false === submit.call(form, success, error)) {
                            return false;
                        }
                    }
                    var type = form.attr("method") ? form.attr("method").toUpperCase() : 'GET';
                    type = type && (type === 'GET' || type === 'POST') ? type : 'GET';
                    var url = form.attr("action");
                    url = url ? url : location.href;
                    // 调整 serialize 方法以收集修改过的数据
                    var file = form.find("input[name=file]");
                    // 构建最终的提交数据
                    var params = $.param({file: file.size() > 0 ? file.val() : '', 'curtimes':curtimes, lastrow, project_id:$('#c-project_id').val()});
                    // 修复当存在多选项元素时提交的 BUG
                    var multipleList = $("[name$='[]']", form);
                    if (multipleList.size() > 0) {
                        var postFields = form.serializeArray().map(function (obj) {
                            return obj.name;
                        });
                        $.each(multipleList, function (i, j) {
                            if (postFields.indexOf($(this).prop("name")) < 0) {
                                params[$(this).prop("name")] = '';
                            }
                        });
                    }
                
                    // 调用 Ajax 请求方法
                    // 返回一个新的Promise对象
                    return new Promise(function(resolve, reject) {
                        Fast.api.ajax({
                            type: type,
                            url: url,
                            data: params,
                            dataType: 'json',
                            complete: function (xhr) {
                                var token = xhr.getResponseHeader('__token__');
                                if (token) {
                                    $("input[name='__token__']").val(token);
                                }
                            }
                        }, function (data, ret) {
                            $('.form-group', form).removeClass('has-feedback has-success has-error');
                            if (data && typeof data === 'object') {
                                // 刷新客户端 token
                                if (typeof data.token !== 'undefined') {
                                    $("input[name='__token__']").val(data.token);
                                }
                                // 调用客户端事件
                                if (typeof data.callback !== 'undefined' && typeof data.callback === 'function') {
                                    data.callback.call(form, data);
                                }
                            }
                            if (typeof success === 'function') {
                                if (false === success.call(form, data, ret)) {
                                    return false;
                                }
                            }
                            resolve(ret); // 解析Promise
                        }, function (data, ret) {
                            if (data && typeof data === 'object' && typeof data.token !== 'undefined') {
                                $("input[name='__token__']").val(data.token);
                            }
                            if (typeof error === 'function') {
                                if (false === error.call(form, data, ret)) {
                                    return false;
                                }
                            }
                            reject(ret); // 拒绝Promise
                        });
                        return true;
                    });
                }
                $('#import-submit').click(function () {
                    var that = this,
                    form = $('#import-form'),
                    submitBtn = $(".layer-footer [type=submit]", form);
                    submitBtn.addClass("disabled");
                    async function submitForm(i) {
                        curtimes = i;
                        try {
                            const rets = await submit(form, function(data, ret){
                                if (ret.code == 1) {
                                    lastrow = ret.data.lastrow;
                                }
                                if ((i + 1) === batchtimes) {
                                    submitBtn.removeClass("disabled");
                                    // 提示及关闭当前窗口
                                    var msg = ret.hasOwnProperty("msg") && ret.msg !== "" ? ret.msg : __('Operation completed');
                                    parent.Toastr.success(msg);
                                    parent.$(".btn-refresh").trigger("click");
                                    var index = parent.Layer.getFrameIndex(window.name);
                                    parent.Layer.close(index);
                                }
                            }, function(data, ret){
                                if ((i + 1) === batchtimes) {
                                    submitBtn.removeClass("disabled");
                                }
                            });
                            // 如果需要根据`ret`做进一步处理
                            // console.log('Submit result:', rets);
                        } catch (error) {
                            // 处理错误情况
                            console.error('Error submitting form:', error);
                        }
                    }
                    
                    (async function processNext() {
                        for (let i = 0; i < batchtimes; i++) {
                            await submitForm(i); // 等待当前提交完成
                        }
                    })();
                    
                    return false
                })
            }
        }
    };
    return Controller;
});
